<?php

namespace app\api\controller;

use app\admin\model\user\UserMember;
use app\api\logic\SmsLogic;
use app\api\logic\UserLogic;
use app\api\model\UserCollection;
use app\api\model\UserMemberDownloadLog;
use app\basic\ApiController;
use hg\apidoc\annotation as Apidoc;
use support\utils\Date;
use think\Validate;
use yzh52521\WebmanLock\Locker;

/**
 * @Apidoc\Title("会员接口")
 */
class UserController extends ApiController
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['login', 'register', 'resetpwd', 'logout'];

    /**
     * 构造方法
     */
    public function __Construct()
    {
        parent::__construct();
        // 存储配置信息
        $this->logic = new UserLogic();
    }

    /**
     * @Apidoc\Title("会员中心")
     * @Apidoc\Method("POST")
     */
    public function index()
    {
        $info = $this->auth->getUserinfo();
         // 查询已下载数量
        $downloadCount = (new UserMemberDownloadLog())->where(['user_id' => $info['id']])->count();
        // 查询我的收藏数量
        $collectCount = (new UserCollection())->where(['user_id' => $info['id']])->count();

        $info['download_count'] = $downloadCount;
        $info['collect_count'] = $collectCount;
        return $this->success($info);
    }



    /**
     * @Apidoc\Title("会员登录")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("account", type="string", require=true, desc="账号",example="18519179004")
     * @Apidoc\Param("password", type="string", require=true, desc="密码",example="123456")
     */
    public function login()
    {
        $account = $this->request->post("account");
        $password = $this->request->post("password");
        if (!$account || !$password) {
            return $this->fail("请输入账户或者密码");
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            return $this->success($data);
        } else {
            return $this->fail($this->auth->getError());
        }
    }

     /**
     * @Apidoc\Title("注册会员")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("account", type="string", require=true, desc="手机号")
     * @Apidoc\Param("password", type="string", require=true, desc="密码")
     * @Apidoc\Param("code", type="string", require=true, desc="密码")
     * @Apidoc\Param("invite_code", type="string", require=true, desc="邀请码")
     */
    public function register()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        $code = $this->request->post('code');
        $invite_code = $this->request->post('invite_code');
        $ret = SmsLogic::check($account, $code, 'register');
        if (!$ret && !getenv('debug')) {
            return $this->fail("验证码错误");
        }
        $lockKey = "user:register:account:{$account}";
        $lock = Locker::lock($lockKey,Date::MINUTE);
        if(!$lock->acquire()){
            return $this->fail("正在注册中，请稍后重试");
        }
        // 增加效验
        $ret = $this->auth->register($account, $password, $account, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            return $this->success('注册成功',$data);
        } else {
            $lock->release();
            return $this->fail($this->auth->getError());
        }
    }

    /**
     * @Apidoc\Title("修改信息")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("nickname", type="string", require=true, desc="昵称")
     * @Apidoc\Param("avatar", type="string", require=true, desc="头像")
     */
    public function profile()
    {
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar');
        $data = [];
        $user = $this->logic->where("id",$this->auth->id)->find();
        if(empty($user)){
            return $this->fail("用户不存在");
        }
        if ($nickname) {
            $data['nickname'] = $nickname;
        }
        if ($avatar) {
            $data['avatar'] = $avatar;
        }
        $user->save($data);
        return $this->success("修改成功");
    }

    /**
     * @Apidoc\Title("修改手机号")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("mobile", type="string", require=true, desc="手机号")
     * @Apidoc\Param("code", type="string", require=true, desc="验证码")
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$mobile || !$code) {
            return $this->fail("Invalid parameters");
        }
        if ($user::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            return $this->fail('Email already exists');
        }
        $ret = SmsLogic::check($mobile, $code, 'changemobile');
        if (!$ret && !getenv('debug')) {
            return $this->fail("验证码错误");
        }
        $user->mobile = $mobile;
        $user->save();
        return $this->success("修改成功");
    }


    /**
     * @Apidoc\Title("重置密码")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("mobile", type="string", require=true, desc="手机号")
     * @Apidoc\Param("newpassword", type="string", require=true, desc="新密码")
     * @Apidoc\Param("code", type="string", require=true, desc="验证码")
     */
    public function resetpwd()
    {
        $mobile      = $this->request->post("mobile");
        $newpassword = $this->request->post("newpassword");
        $captcha     = $this->request->post("code");
//        if (!$newpassword || !$captcha) {
//            return $this->fail('Invalid parameters');
//        }
        $Validate = new Validate();
        //验证Token
        if (!$Validate->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            return $this->fail('Password must be 6 to 30 characters');
        }
        if (!$Validate->regex($mobile, "^1\d{10}$")) {
                return $this->fail('Mobile is incorrect');
        }
        $user = UserMember::getByMobile($mobile);
        if (!$user) {
            return $this->fail('User not found');
        }
//        $ret = SmsLogic::check($mobile, $captcha, 'resetpwd');
//        if (!$ret) {
//            return $this->fail('Captcha is incorrect');
//        }
//        SmsLogic::flush($mobile, 'resetpwd');
        //模拟一次登录
        $ret = $this->auth->changepwd($newpassword, '', true);
        $this->auth->direct($user->id);
        if ($ret) {
            return $this->success('修改密码成功');
        } else {
            return $this->fail($this->auth->getError());
        }
    }



    /**
     * @Apidoc\Title("退出登录")
     * @Apidoc\Method("POST")
     */
    public function logout()
    {
        if (!$this->request->method("POST")) {
            return $this->fail("未知错误");
        }
        $this->auth->logout();
        return $this->success("","退出成功");
    }

}